package com.activity.controller;

import com.activity.common.aop.OperLog;
import com.activity.common.result.Result;
import com.activity.common.util.FileDfsUtil;
import com.activity.common.util.FileUtil;
import com.activity.common.util.TokenVerify;
import com.activity.entity.Department;
import com.activity.entity.News;
import com.activity.entity.Resourceurl;
import com.activity.service.NewsService;
import com.activity.service.impl.NewsServiceImpl;
import com.activity.service.impl.ResourceServiceImpl;
import com.alibaba.druid.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Api
@RestController
@RequestMapping("/upload")
public class ResourceController {

    @Autowired
    private ResourceServiceImpl resourceService;

//    @Autowired
//    private FileDfsUtil fileDfsUtil;



    /**
     * 显示资源表中的所有信息
     */
    @PostMapping("/showAll")
    @TokenVerify()
    public Result showAll(){
        List<Resourceurl> resourceurls = resourceService.showAll();
        if (resourceurls.size()>0)
        {
            return Result.success("查询资源成功",resourceurls);
        }else{
            return Result.fail("查询资源失败");
        }
    }

//    /**
//     * 图片上传
//     * @param file
//     * @return
//     */
//    @ApiOperation(value = "上传文件", notes = "存储服务器仅支持以下格式:png、gif、jpg、jpeg、bmp")
//    @PostMapping("/uploadPicture")
//    public Result uploadFile(@RequestParam("file") MultipartFile file,Integer id) {
//        String fileName = file.getName();
//        try {
//            //上传文件
//            String path = fileDfsUtil.upload(file);
//            if (!StringUtils.isEmpty(path)) {
//                Resourceurl resourceurl = new Resourceurl();
//                resourceurl.setNewsid(id);
//                resourceurl.setType("v");
//                resourceurl.setResourceurl(path);
//                boolean b = resourceService.insertPicture(resourceurl);
//                if (b){
//                    return Result.success(path);
//                }else{
//                    return Result.fail("上传服务器成功,但是存储数据库失败");
//                }
//            }
//        } catch (Exception e) {
//            return Result.fail("存储服务出现异常");
//        }
//        return Result.fail("出错了");
//    }


    @GetMapping("/getResourceById/{id}")
    @TokenVerify()
    public Result selectAll(@PathVariable Integer id){
        List<Resourceurl> resourceurls = resourceService.selectByNewsId(id);
        if(resourceurls.size()>0){
            return Result.success("查询资源成功",resourceurls);
        }else {
            return Result.fail("查询失败");
        }
    }

    @PostMapping("/addparent")
    @TokenVerify()
    @ResponseBody
    public String upFile(@RequestParam("file") MultipartFile file, Integer id) {
        String path = "D:/activityResourceUrl/";
        String fileName = file.getOriginalFilename();
        String suffixName=fileName.substring(fileName.lastIndexOf("."));
        fileName= UUID.randomUUID()+suffixName;


        String imgString=".png+.jpg+.gif+.bmp+.psd+.+jpeg+.tif+.PNG+.JPEG";
        String videoString=".mp4+.mov+.AVI+.3GP+.ASF+.MPEG";
        //判断文件类型
        Resourceurl resourceurl = new Resourceurl();
        if(imgString.contains(suffixName)){
            resourceurl.setType("i");
        }else if (videoString.contains(suffixName)){
            resourceurl.setType("v");
        }else{

        }
        resourceurl.setResourceurl(path+fileName);
        resourceurl.setNewsid(id);
        boolean b = resourceService.insertPicture(resourceurl);


        File targetFile = new File(path);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        File saveFile = new File(targetFile, fileName);
        try {
            file.transferTo(saveFile);
        } catch (Exception e) {
            e.printStackTrace();
            return "failed";
        }
        return "success";
    }


    @GetMapping("/deleteById/{id}")
    @TokenVerify()
    public Result deleteById(@PathVariable Integer id){
        boolean b = resourceService.deleteById(id);
        if (b){
            return  Result.success("删除成功");
        }else {
            return Result.fail("删除失败");
        }
    }

    @GetMapping("/addparent/{id}")
    @TokenVerify()
    @ResponseBody
    public void showfile(@PathVariable Integer id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取图片
        Resourceurl resourceurl = resourceService.selectById(id);


        String url=resourceurl.getResourceurl();
            //如果返回的类型是图片设置 response.setContentType("image/png");
            //如果返回的类型是视频
            if (url.contains("png")||url.contains("jpg")){
                response.setContentType("image/png");
            }else if (url.contains("mp4")){
                response.setContentType("application/ogg");
            }
            File file = new File(resourceurl.getResourceurl());
            //创建文件输入流
            FileInputStream is = new FileInputStream(file);
            // 响应输出流
            ServletOutputStream out = response.getOutputStream();
            // 创建缓冲区
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            is.close();
            out.flush();
            out.close();
        }


}
